package com.foreknow.reflection;

import java.awt.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ReflectionDemo {

    public void getNameTest(){
        String name = "tom123";
        Class cls = name.getClass();
        System.out.println("String类的名称是："+cls.getName());
        Button btn = new Button();
        Class btnClass = btn.getClass();
        System.out.println("Button类的名称是："+btnClass.getName());
        Class superclass = btnClass.getSuperclass();
        System.out.println("Button父类类的名称是："+superclass.getName());
    }

    public String testMethod(String str, Map hashMap){
        String returnStr = "这是当前方法要返回的字符串";
        System.out.println("获取到Map中的数据"+hashMap.get("name"));
        return returnStr;
    }

    //通过反射动态调用testMethod(String str, Map hashMap)方法
    public void getMethodTest() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //1.获取到当前类的对象
        Class cls = Class.forName("com.foreknow.reflection.ReflectionDemo");
        //2.获取要调用的当前类对象的方法的名称
        //两个参数：1，name 要获取的方法的名称  2.parameterType 表示参数的类型
        Class[] ptypes = new Class[2];
        ptypes[0] = Class.forName("java.lang.String");
        ptypes[1] = Class.forName("java.util.Map");
        Method method = cls.getMethod("testMethod", ptypes);
        //3.调用testMethod方法
        Object[] args = new Object[2];
        args[0]="3afs";
        HashMap hashMap = new HashMap();
        hashMap.put("name","fender........");
        args[1] = hashMap;
        String str = (String) method.invoke(new ReflectionDemo(), args);
        System.out.println(str);
    }

    public static void main(String[] args) {
        ReflectionDemo rd = new ReflectionDemo();
        rd.getNameTest();
        try {
            rd.getMethodTest();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
